using System;
using System.IO;
using UnityEngine;

public class FileDataHandler
{
    private string directory;
    private string fileName;
    private bool encryptData;
    private string codeWord = "华夏";

    public FileDataHandler(string directory, string fileName, bool encryptData = false)
    {
        this.directory = directory;
        this.fileName = fileName;
        this.encryptData = encryptData;
    }

    public void Save(GameData data)
    {
        if (directory == null || fileName == null) return;
        string fullPath = Path.Combine(directory, fileName);
        try
        {
            _ = Directory.CreateDirectory(Path.GetDirectoryName(fullPath) ?? string.Empty);
            string dataToStore = JsonUtility.ToJson(data, true);
            if (encryptData)
            {
                dataToStore = EncryptDecrypt(dataToStore);
            }
            using FileStream fs = new FileStream(fullPath, FileMode.Create);
            using StreamWriter sw = new StreamWriter(fs);
            sw.Write(dataToStore);
        }
        catch (Exception)
        {
            throw;
        }
    }

    private string EncryptDecrypt(string data)
    {
        string modifieData = string.Empty;
        // j ^ R = 1
        // 1 ^ R = j
        for (int i = 0; i < data.Length; i++)
        {
            char modifiedChar = (char)(data[i] ^ codeWord[i % codeWord.Length]);
            modifieData += modifiedChar;
        }
        return modifieData;
    }

    public GameData Load()
    {
        string fullPath = Path.Combine(directory, fileName);
        GameData data = null;
        if (!File.Exists(fullPath))
        {
            return data;
        }
        try
        {
            string dataToLoad;
            using (FileStream fs = new FileStream(fullPath, FileMode.Open))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    dataToLoad = sr.ReadToEnd();
                }
            }
            if (encryptData)
            {
                dataToLoad = EncryptDecrypt(dataToLoad);
            }
            data = JsonUtility.FromJson<GameData>(dataToLoad);
        }
        catch (Exception)
        {
            throw;
        }
        return data;
    }

    public void Delete()
    {
        string fullPath = Path.Combine(directory, fileName);
        if (!File.Exists(fullPath))
        {
            return;
        }
        try
        {
            File.Delete(fullPath);
        }
        catch (Exception) { }
    }

#if UNITY_EDITOR
    [UnityEditor.MenuItem("Tools/Open Save Directory")]
    public static void OpenSaveDirectory()
    {
        string path = Path.Combine(Application.persistentDataPath, Application.productName);
        UnityEditor.EditorUtility.RevealInFinder(path);
    }
#endif
}